import dayjs from "dayjs"
import { removeConfigLayout } from "@/utils/cache/local-storage"

/** 格式化时间 */
export const formatDateTime = (time: string | number | Date) => {
  return time ? dayjs(new Date(time)).format("YYYY-MM-DD HH:mm:ss") : "N/A"
}

/** 用 JS 获取全局 css 变量 */
export const getCssVariableValue = (cssVariableName: string) => {
  let cssVariableValue = ""
  try {
    // 没有拿到值时，会返回空串
    cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
  } catch (error) {
    console.error(error)
  }
  return cssVariableValue
}

/** 用 JS 设置全局 CSS 变量 */
export const setCssVariableValue = (cssVariableName: string, cssVariableValue: string) => {
  try {
    document.documentElement.style.setProperty(cssVariableName, cssVariableValue)
  } catch (error) {
    console.error(error)
  }
}

/** 重置项目配置 */
export const resetConfigLayout = () => {
  removeConfigLayout()
  location.reload()
}

// 生成uuid
export function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

//数组转树状
export const buildTree = (arr, parentId = null, visited = {}) => {
  const tree = [];
  arr.forEach(item => {
      if (item.parentId === parentId && !visited[item.menuId]) {
          visited[item.menuId] = true;
          const children = buildTree(arr, item.menuId, visited);
          if (children.length) {
              item.children = children;
          }
          tree.push(item);
      }
  });
  return tree;
}

export const download = (fileArrayBuffer:any , filename:any) => {
  let data = new Blob([fileArrayBuffer], { type: 'application/vnd.ms-excel,charset=utf-8' });
  if (typeof window.chrome !== 'undefined') {
    // Chrome
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(data);
    link.download = filename;
    link.click();
  } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // IE
    var blob = new Blob([data], { type: 'application/force-download' });
    window.navigator.msSaveBlob(blob, filename);
  } else {
    // Firefox
    var file = new File([data], filename, { type: 'application/force-download' });
    window.open(URL.createObjectURL(file));
  }
};


export function generateRandomString(length: number) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  return Array.from({ length })
    .reduce((result) => result + characters.charAt(Math.floor(Math.random() * characters.length)), '');
}

export const debounce = function(fn, wait = 1000, immediately = true) {
	let timer;
	return function() {
		let that = this,
			args = arguments;
		if (timer) clearTimeout(timer);
		if (immediately) {
			let callNow = !timer;
			timer = setTimeout(() => {
				timer = null;
			}, wait);
			if (callNow) fn.apply(that, args);
		} else {
			timer = setTimeout(() => {
				fn.apply(that, args);
			}, wait)
		}
	}
}

export const propTypes = () => ({
  string: {
    def: (defaultValue: string) => ({ type: String, default: defaultValue })
  },
  oneOfType: (types: any[]) => ({
    def: (defaultValue: any) => ({ type: types, default: defaultValue })
  }),
  bool: {
    def: (defaultValue: boolean) => ({ type: Boolean, default: defaultValue })
  }
})
